package com.gitee.starblues.grape.core.service;


import com.gitee.starblues.grape.core.builder.RebateAccountBuilder;
import com.gitee.starblues.grape.core.builder.RebateAccountLogBuilder;
import com.gitee.starblues.grape.core.builder.RebateDrawLogBuilder;
import com.gitee.starblues.grape.core.builder.RebateOrderBuilder;
import com.gitee.starblues.grape.core.domain.user.*;
import com.gitee.starblues.grape.core.exception.ChailvErrorCode;
import com.gitee.starblues.grape.core.exception.ChailvException;
import com.gitee.starblues.grape.repository.databases.entity.*;
import com.gitee.starblues.grape.repository.databases.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Repository
public class UserRepository {

	private static Logger logger = LoggerFactory.getLogger(UserRepository.class);

	@Resource
	private RebateOrderMapper rebateOrderMapper;

	@Resource
	private RebateAccountLogMapper rebateAccountLogMapper;

	@Resource
	private RebateAccountMapper rebateAccountMapper;

	@Resource
	private RebateDrawLogMapper rebateDrawLogMapper;

	@Resource
	private UserAccountMapper userAccountMapper;

	/**
	 * 获取返利订单
	 *
	 * @param currentUsername 当前用户名
	 * @param pageNum         页码
	 * @param pageSize        每页大小
	 * @param status          订单状态
	 * @return 分页后的返利订单列表
	 */
	public PageInfo<RebateOrder> loadRebateOrders(String currentUsername, int pageNum, int pageSize, Integer status) {
		PageInfo<RebateOrder> page = new PageInfo<>();
		try {
			PageHelper.startPage(pageNum, pageSize);
			// 修改为根据用户名和状态查询
			List<RebateOrderPo> source = rebateOrderMapper.selectRebateOrdersByUserNameAndStatus(currentUsername, status);
			if (source != null && !CollectionUtils.isEmpty(source)) {
				List<RebateOrder> rebateOrders = RebateOrderBuilder.build(source);
				page.setList(rebateOrders);
				page.setPageNum(pageNum);
				page.setPageSize(pageSize);
				// 修改为根据用户名和状态统计
				page.setTotal(rebateOrderMapper.countRebateOrdersByUserNameAndStatus(currentUsername, status));
			}
			return page;
		} catch (Exception e) {
			logger.error("userName:{}获取返利订单错误", currentUsername, e);
			return new PageInfo<>(Collections.emptyList());
		}
	}

	/**
	 * 添加返利订单
	 *
	 * @param order
	 */
	public void addRebateOrder(RebateOrder order) {
		RebateOrderPo record = RebateOrderBuilder.build(order);
		rebateOrderMapper.insertSelective(record);
	}

	/**
	 * 获取提现记录
	 *
	 * @param currentUsername 当前用户名
	 * @return
	 */
	public List<RebateDrawLog> loadRebateDrawLogs(String currentUsername) {
		List<RebateDrawLogPo> listPo = rebateDrawLogMapper.selectRebateDrawLogByUserName(currentUsername);
		return RebateDrawLogBuilder.build(listPo);
	}

	/**
	 * 添加提现记录
	 *
	 * @param drawLog
	 * @throws ChailvException
	 */
	public void addRebateDrawLog(RebateDrawLog drawLog) throws ChailvException {
		// 根据用户名查询账户信息

		RebateAccountPo account = rebateAccountMapper.selectRebateAccountByUserName(drawLog.getUserName());
		if (account == null) {
			throw new ChailvException(ChailvErrorCode.ACCOUNT_NOT_EXIST, "账户未建立，无钱可提");
		}
		int r = account.getAvailableBalance().compareTo(drawLog.getAmount());
		if (r < 0) {
			logger.info("userName:{}提取的钱比余额还多，赶紧看问题", drawLog.getUserName());
			throw new ChailvException(ChailvErrorCode.DRAW_AMOUNT_ERROR, "账户无钱，还来提钱？");
		} else {
			rebateDrawLogMapper.insertSelective(RebateDrawLogBuilder.build(drawLog));
		}
	}

	/**
	 * 返利收支明细
	 *
	 * @param currentUsername 当前用户名
	 * @return
	 */
	public List<RebateAccountLog> loadRebateAccountLogs(String currentUsername) {
		try {
			List<RebateAccountLogPo> source = rebateAccountLogMapper.selectRebateAccountLogsByUserName(currentUsername);
			return RebateAccountLogBuilder.build(source);
		} catch (Exception e) {
			logger.error("userName:{}获取返利收支明细错误", currentUsername, e);
			return Collections.emptyList();
		}
	}

	/**
	 * 获取返利账户信息
	 *
	 * @param currentUsername 当前用户名
	 * @return
	 */
	public RebateAccount loadRebateAccount(String currentUsername) {
		try {
			RebateAccountPo po = rebateAccountMapper.selectRebateAccountByUserName(currentUsername);
			if (po == null) {
				return buildDefaultAccount(currentUsername);
			}
			return RebateAccountBuilder.build(po);
		} catch (Exception e) {
			logger.error("userName:{}获取返利账户信息错误", currentUsername, e);
			return buildDefaultAccount(currentUsername);
		}
	}

	private RebateAccount buildDefaultAccount(String currentUsername) {
		RebateAccount entity = new RebateAccount();
		entity.setUserId(currentUsername);
		return entity;
	}


	public List<UserAccount> loadUserAccounts(String userName) {
		List<UserAccountPo> userAccountPos = userAccountMapper.selectUserAccountsByUserName(userName);
		return userAccountPos.stream()
				.map(this::convertToUserAccount)
				.collect(Collectors.toList());
	}


	public void addUserAccount(UserAccount userAccount) {
		UserAccountPo userAccountPo = convertToUserAccountPo(userAccount);
		userAccountMapper.insertUserAccount(userAccountPo);
	}

	/**
	 * 更新用户账户
	 */
	public void updateUserAccount(UserAccount userAccount) {
		UserAccountPo userAccountPo = convertToUserAccountPo(userAccount);
		userAccountMapper.updateUserAccount(userAccountPo);
	}

	private UserAccount convertToUserAccount(UserAccountPo po) {
		UserAccount userAccount = new UserAccount();
		userAccount.setId(po.getId());
		userAccount.setAccountName(po.getAccountName());
		userAccount.setAccountType(po.getAccountType());
		userAccount.setUserId(po.getUserId());
		userAccount.setUserName(po.getUserName());
		userAccount.setInsertedTime(po.getInsertedTime());
		userAccount.setUpdatedTime(po.getUpdatedTime());
		userAccount.setDeleteFlag(po.getDeleteFlag());
		return userAccount;
	}

	private UserAccountPo convertToUserAccountPo(UserAccount userAccount) {
		UserAccountPo po = new UserAccountPo();
		po.setId(userAccount.getId());
		po.setAccountName(userAccount.getAccountName());
		po.setAccountType(userAccount.getAccountType());
		po.setUserId(userAccount.getUserId());
		po.setUserName(userAccount.getUserName());
		po.setInsertedTime(userAccount.getInsertedTime());
		po.setUpdatedTime(userAccount.getUpdatedTime());
		po.setDeleteFlag(userAccount.getDeleteFlag());
		return po;
	}
}









